#pragma once
#include <netinet/in.h>
#include <netinet/tcp.h>
#include"Channel.h"
#include"Connection.h"
#include"InetAddress.h"
#include"Socket.h"
#include"Callback.h"
#include"Core.h"
namespace wjc {
	using namespace net;
	class Acceptor:public std::enable_shared_from_this<Acceptor> {
	private:
		int fd_;
		Socket socket_;
		std::shared_ptr<Channel>channel_;

		Core* core_;
		bool listenning_;

		NewConnectionCallback newConnectionCallback_;
	public:
		Acceptor(Core* core, const InetAddress& listenAddr, bool reuseport);
		~Acceptor();

		bool listenning() const { return listenning_; }
		void listen();
		void unlisten();

		void setNewConnectionCallback(const NewConnectionCallback& cb)
		{
			newConnectionCallback_ = cb;
		}

		void handleRead(Timestamp tm);

		void destruction() {
			auto guard = shared_from_this();
			if (core_->isInCoreThread()) {
				channel_->disableAll();
				channel_->remove();
			}
			else {
				core_->runInCore(CreateTask(std::bind(&Acceptor::destruction, guard)));
			}
		}
	};
}
